# BannerController
#
# @description :: Server-side logic for managing banners
# @help        :: See http://sailsjs.org/#!/documentation/concepts/Controllers
path = require 'path'

uploadFileGeneric =  (req, res, maxSize) ->
# don't allow the total upload size to exceed ~1MB
  dir = req.param('dir')
  if !dir
    dir = ''
  req.file('file').upload(
    maxBytes: maxSize
    dirname: './' + dir
    (err, uploadedFiles) ->
      if err
        return res.negotiate(err)
      if uploadedFiles.length == 0
        return res.badRequest('没有要上传的文件.')
      uf = uploadedFiles[0]
      file =
        fd: uf.fd
        size: uf.size
        type: uf.type
        filename: uf.filename
        status: uf.status
        extra: uf.extra
        inUsing: true
      FileUtil.create(file).exec((err, created) ->
#          OssService.upFile2Oss(created.id, file.fd);
        FileUtil.findOne(created.id).exec((err, file) ->
          if err
            return res.negotiate err
          if !file
            return res.notFound
#          redirect = sails.config.appUrl + ':' + sails.config.port + '/file/doc/' + created.id;
          redirect = 'http://admin.sf8cloud.com' + '/file/doc/' + created.id;
#          redirect = '/file/doc/' + created.id; #TODO:在访问文件时加文件服务器的前缀.(前缀应该是配置项).
          return res.json
            url: redirect
            fileName: file.filename
        )
      )
  )

module.exports = {

  uploadImg: (req, res) ->
# don't allow the total upload size to exceed ~1MB
    dir = req.param('dir')
    if !dir
      dir = ''
    req.file('file').upload(
      maxBytes: 50048000
      dirname: './' + dir
      (err, uploadedFiles) ->
        if err
          return res.negotiate(err)
        if uploadedFiles.length == 0
          return res.badRequest('没有要上传的文件.')

        uf = uploadedFiles[0]
        file =
          fd: uf.fd
          size: uf.size
          type: uf.type
          filename: uf.filename
          status: uf.status
          extra: uf.extra
          inUsing: true
        FileUtil.create(file).exec((err, created) ->
          OssService.upFile2Oss(created.id, file.fd, (err, cdnKey)->
            return res.json
              id: created.id
              url: CdnService.CDN_HOST + '/img/' + cdnKey
              fileName: file.filename
          );

        )
    )

  uploadFile: (req, res) ->
    uploadFileGeneric(req, res, 1024000000)

  uploadXls: (req, res) ->
    uploadFileGeneric(req, res, 50048000)

  downloadFile: (req, res) ->
    req.validate
      id: 'string'

    FileUtil.findOne(req.param('id')).exec((err, file) ->
      if err
        return res.negotiate err
      if !file
        return res.notFound

      filename = file.filename
      lastDot = filename.lastIndexOf('.')
      suf = '';
      if(lastDot != -1)
        suf = filename.substring(lastDot)

      return res.download(file.fd, file.id + suf)

#      SkipperDisk = require('skipper-disk')
#      fileAdapter = SkipperDisk()
#
#      # stream the file down
#      fileAdapter.read(file.fd)
#      .on('error', (err) ->
#        return res.notFound
#      ).pipe(res)
    )

#  cdnImg: (req, res) ->
#    req.validate
#      id: 'string'
#    res.redirect('http://img2.kissbaby-toys.cn/img/573eb4aad6444a2408008b41?cdn=true')

  img: (req, res) ->
    req.validate
      id: 'string'

    FileUtil.findOne(req.param('id')).exec((err, file) ->
      if err
        return res.negotiate err
      if !file
        return res.notFound

      if file.cdnPath
        redirect = CdnService.CDN_HOST + file.cdnPath;
        return res.redirect(redirect)

      SkipperDisk = require('skipper-disk')
      fileAdapter = SkipperDisk()


      # stream the file down
      fileAdapter.read(file.fd)
      .on('error', (err) ->
#        return res.redirect('/genImg/360x240')
#使用默认图片
        defaultImg = path.resolve(sails.config.appPath, 'assets/images/default_image.gif')
        fileAdapter.read(defaultImg)
        .on('error', (err) ->
          return res.serverError err
        ).pipe(res)
      ).pipe(res)
    )

  genImg: (req, res) ->
    ImgPlaceholder.genImg(req, res, ()->
#使用默认图片
      defaultImg = path.resolve(sails.config.appPath, 'assets/images/default_image.gif')
      SkipperDisk = require('skipper-disk')
      fileAdapter = SkipperDisk()
      fileAdapter.read(defaultImg)
      .on('error', (err) ->
        return res.serverError err
      ).pipe(res)
    )

}
